FILE_LOCATION   =	"/ifs/scratch/c2b2/ip_lab/ddd2124"

setwd(FILE_LOCATION)

SIB_FILE<-read.table("siblings.lst",header=F,stringsAsFactors=F)

poplist<-read.table("PopIndex.txt",header=F, stringsAsFactors=F)
poplist<-poplist[,1]


#enact these once you have the lengths and numbers files
Lengths<-read.table("Lengths.txt",header=F)
Numbers<-read.table("Numbers.txt",header=F)

}

sibl<-integer(0)
sibn<-integer(0)

for (i in seq(length(SIB_FILE[,1])))
{
	if ((A<-which(poplist==SIB_FILE[i,1]))<(B<-which(poplist==SIB_FILE[i,2])))
	{sibl<-c(sibl,Lengths[A,B])
	 sibn<-c(sibn,Numbers[A,B])}
	else 	{sibl<-c(sibl,Lengths[B,A])
		 sibn<-c(sibn,Numbers[B,A])}
}

siblcdf<-ecdf(sibl)
sibncdf<-ecdf(sibn)


g<-length(Lengths[,1])


#####################################################
##################SIB MATRICES#######################

SIBNMAT <- Lengths
for (i in seq(g-1))
{
	SIBNMAT[i,] <- sibncdf(Numbers[i,])
	SIBNMAT[i,] <- apply(rbind(SIBNMAT[i,],1-SIBNMAT[i,]), 2, min)
}

SIBLMAT <- PCNMAT
for (i in seq(g-1))
{
	SIBLMAT [i,] <- siblcdf(Lengths[i,])
	SIBLMAT [i,] <- apply(rbind(SIBLMAT [i,],1-SIBLMAT [i,]), 2, min)
}

SIBNMAT2 <-SIBNMAT + t(SIBNMAT)
write.table(SIBNMAT2,"SIBNMAT.txt",row.names=F,col.names=F,quote=F)
rm(SIBNMAT2, SIBNMAT)
gc()
SIBLMAT2 <- SIBLMAT + t(SIBLMAT)
write.table(SIBLMAT2 ,"SIBLMAT.txt",row.names=F,col.names=F,quote=F)
rm(SIBLMAT2, SIBLMAT)
gc()

###############################################################################
# add matrices for avg lengths

AverageLengths <- Numbers / (Lengths + .001)
siba<-integer(0)

g<-length(AverageLengths[,1])

for (i in seq(length(SIB_FILE[,1])))
{
	if ((A<-which(poplist==SIB_FILE[i,1]))<(B<-which(poplist==SIB_FILE[i,2])))
	{siba<-c(siba,AverageLengths[A,B])}
	else 	{siba<-c(siba,AverageLengths[B,A])}
}

sibacdf<-ecdf(siba)

SIBAMAT<- AverageLengths
for (i in seq(g-1))
{
	SIBAMAT[i,] <- sibacdf(AverageLengths[i,])
	SIBAMAT[i,] <- apply(rbind(SIBAMAT[i,],1-SIBAMAT[i,]), 2, min)
}

SIBAMAT<- SIBAMAT+ t(SIBAMAT)
write.table(SIBAMAT,"SIBAMAT.txt",row.names=F,col.names=F,quote=F)
rm(SIBAMAT, siba, sibacdf)
gc()

################
quit()